import requests
import os
from bs4 import BeautifulSoup as bs


def getpage():
	'''
	根据url和请求头爬取购物车信息
	购物车商品已选择两个 分别为：
	百草味夏威夷果
	联想游戏本
	'''
	url = 'https://cart.jd.com/cart.action'

	headers = {
		'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',
		'Accept-Encoding': 'gzip, deflate, br',
		'Accept-Language': 'zh-CN,zh;q=0.9',
		'Cache-Control': 'no-cache',
		'Connection': 'keep-alive',
		'Cookies': 'shshshfpa=cd0559a2-763f-9751-3466-20b1d53bf83c-1533560598; shshshfpb=0e0bef53e92c3377275c2d6d44e574412b8394331c7ce2d8b5b6847178; PCSYCityID=country_2468; user-key=a6626ab1-68e2-4702-8036-54b7ec13df37; ipLocation=%u5317%u4eac; cd=0; ipLoc-djd=1-2805-2832-0.138543703; unpl=V2_ZzNtbUoHERN9XEVVexlfAmICFVURV0dAcwlDVXkaWwxnAhFeclRCFXwUR1xnGVkUZwQZXUFcRxFFCHZXfBpaAmEBFl5yBBNNIEwEACtaDlwJBBpUSlNEHXwLTlZLKV8FVwMTbUReQRV3C0VcfylsAlczIllFVkIQcDhHZHopHlE7ChNbQlRDWHMBRFR5Gl8NYzMTbUE%3d; __jdv=122270672|baidu-search|t_262767352_baidusearch|cpc|69895698293_0_9ac79e2011264069b15d704032681022|1536912775808; mt_xid=V2_52007VwUbUF1aUVkXTSlbUWMAQgVeCk4NHUAQQAA3U0JOVF9aWgMdEVkHNVRAW1kMUg8vShhcDHsCGk5dXUNaGEIZXg5lBiJQbVtiWR5PEVkAVwAVUls%3D; __jdc=122270672; shshshfp=e2519bab84dc349aaff1bde0bb5769dd; TrackID=1lJMPyb4DKZZjRLFuD00H2qZ1CYIfls9fidakJHyOQ6-S2D31YvrKctLc8fdiifBFdUqlvptfzru0usqkhZM61GTzDp6ftXkazoDiIuC3Y94; pinId=vpSsGEreESgJkbkGcPh7Qw; pin=%E5%BC%A0%E6%98%9F%E6%98%9F-qq; unick=limit-12345; ceshi3.com=103; _tp=QQaf%2BitefpsonMuL0icZqymyxoHUcfWbYKpTfb1Anf8%3D; _pst=%E5%BC%A0%E6%98%9F%E6%98%9F-qq; __jda=122270672.783132295.1533560595.1537260620.1537269087.11; cart-main=xx; cn=12; 3AB9D23F7A4B3C9B=PXYEXGCCBFIK4XBT6XVKADFXHD7O55SON5AMTNOXN6NLSLR737B2YG3BJHPX6FYWWAIJRRTGID6YTPA4FIWBPPXJLM; shshshsID=a5f405def6c8fd3f24c218e9bd933152_3_1537269314654; __jdb=122270672.5.783132295|11.1537269087; __jdu=15372697248171772875325; thor=395D7B245147382A3338637935B35D10CD8F17AD34EBF3672DE6D53AA4F113302519159661C6573B21D54CDEF4E8D2B2AC710E9417045E6E4D55A4F172AA2DB03868CE4433A661BC3800A0D8C84FB605E8364BDEA80FA4C30A5480AD02FF8735C2EAED10A7AC544A177904A5AE2D651CC0E4AD7FBB0B97F0A2ACE7D0896462C0',
		'Host': 'cart.jd.com',
		'Pragma': 'no-cache',
		'Referer': 'https://home.jd.com/',
		'Upgrade-Insecure-Requests': '1',
		'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36',
	}

	try:
		res = requests.get(url, headers=headers)
		if res.status_code == 200:
			return res.text
		else:
			print(1)
			return None
	except Exception as err:
		print("爬取失败，原因是："+str(err))
		return None

def parsepage(content):
	'''解析html，获取商品的商品名、颜色、价格、单价、数量、总价、小结等信息'''
	if content:
		soup = bs(content, 'lxml')
		items = soup.find_all(name="div", attrs={"product":"1"})
		for item in items:
			yield {
				'title': item.find(name="div",attrs={'class': 'p-name'}).a.get_text().strip(),
				'color': item.find(name="div",attrs={'class': 'props-txt'}).string.strip(),
				'price': item.find(name="div",attrs={'class': 'cell p-price p-price-new '}).strong.string,
				'quantity': item.find(name="input",attrs={'autocomplete': 'off'}).attrs['value'],
				'total': item.find(name="div",attrs={'class': 'cell p-sum'}).strong.string,
				'all': soup.find(name="span",attrs={"class": "price sumPrice"}).em.get_text()
			}

def showpage(content,no):
	'''打印购物车信息'''
	if content:
		print("第"+str(no)+"件商品信息")
		print("名称："+content['title'])
		print(content['color'])
		print("单价："+content['price'])
		print("数量："+content['quantity'])
		print("总价："+content['total'])


def main():
	html = getpage()
	items = list(parsepage(html))
	no = 1
	print("当前京东购物车有"+str(len(items))+"件商品")
	for item in items:
		showpage(item, no)
		no = no+1
	print("当前购物车商品总价为："+items[0]['all']+"元")


if __name__ == '__main__':
	main()
